import java.util.*;

public class Sale {

	boolean isPaid;
	boolean isReady;
	private ArrayList<SaleItem> itemList;
	private Date date;
	private ICCAdapter payment;
	private PaymentAuthorizationService source;
	private String userGuess;
	
	public Sale () {
	    date = new Date ();
	    isPaid = false;
	    isReady = false;
	    itemList = new ArrayList<SaleItem> ();
	    payment = null;
	    source = new PaymentAuthorizationService ();
	    userGuess = "";
	}
	public boolean isComplete () {
	    // Whether the customer is finished adding items to the order or not.
		return isReady;
	}
    public boolean isPayable () {
        // Whether a method of payment has been validated and confirmed.
        return source.isConfirmed (payment, userGuess);
    }
    public boolean isPaid () {
        // Whether the items of the order have been paid for or not.
        return isPaid;
    }
    public void pinInput (String pin) {
        userGuess = pin;
    }
	public void addItem (AvailableItem item) {
	    int i;
	    for (i = 0; i < itemList.size (); i++) {
	        if (itemList.get (i).getItem ().itemID ().equals (item.itemID ())) {
	            // If the item is already in the list, increment its quantity.
	            itemList.get (i).incQuantity ();
	            break;
	        }
	    }
	    if (i == itemList.size ()) {
	        // If the item is not already in the sale, add it.
	        itemList.add (new SaleItem (item));
	    }
	}
	public double calculateTotalCost () {
		double total = 0;
		for (SaleItem Item: itemList){
			total += Item.getItem ().price ();
		}
	    return total;
	}
	public boolean extractPayment () {
	    double total = calculateTotalCost ();
		if ((payment.getAmount ()) - total < 0) {
			System.out.println ("Insufficient Funds.");
		} else {
		    payment.changeAmount (total);
			isPaid = true;
		}
		return isPaid;
	}
    public void setPayment (String payType) {
    	payment = source.validateCard (payType);
    }
    public ArrayList<SaleItem> getList () {
    	return itemList;
    }
    public void dispenseSoldItems () {
        ItemDispenser dispenser = new ItemDispenser ();
        dispenser.dispenseItems (itemList);
    }
}
